package com.mind.core.util;
public class RadixEncodeing {

	final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
			'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
			'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
			'z' , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
			'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
			'Z','+','-'};

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(num2string(63));
		System.out.println(num2string(64));
		System.out.println(num2string(55));
		System.out.println(num2string(100));
		System.out.println(num2string(132));
		System.out.println(string2num("0"));
		System.out.println(string2num("w"));
		System.out.println(string2num("T"));
		System.out.println(string2num("1A"));
		System.out.println(string2num("24"));
	}

	public static String toUnsignedString(int i, int shift) {
		char[] buf = new char[64];
		int charPos = 64;
		int radix = 1 << shift;
		int mask = radix - 1;
		do {
			buf[--charPos] = digits[(int) (i & mask)];
			i >>>= shift;
		} while (i != 0);

		return new String(buf, charPos, (64 - charPos));
	}

	/**
	 * 
	 * @param number
	 * @param shift
	 * @return
	 */
	public static String num2string(int number) {
		return toUnsignedString(number, 6);
	}
	/**
	 * 
	 * @param number
	 * @param shift
	 * @return
	 */
	public static char num2char(int number) {
		return toUnsignedString(number, 6).charAt(0);
	}
	/**
	 * 
	 * @param decompStr
	 * @return
	 */
	public static long string2num(String decompStr) {
		long result = 0;
		for(int i=decompStr.length()-1;i>=0;i--){
			if (i == decompStr.length() - 1) {
				result += getCharIndexNum(decompStr.charAt(i));
				continue;
			}
			result+=getCharIndexNum(decompStr.charAt(i))<<6;
		}
		return result;
	}

	/**
	 * 
	 * @param ch
	 * @return
	 */
	private static long getCharIndexNum(char ch) {
		int num = ((int) ch);
		if (num >= 48 && num <= 57) {
			return num - 48;
		} else if (num >= 97 && num <= 122) {
			return num - 87;
		} else if (num >= 65 && num <= 90) {
			return num - 29;
		} else if (num == 43) {
			return 62;
		} else if (num == 45) {
			return 63;
		}
		return 0;
	}

}
